package com.parktech.sun.domain.service.notice.impl;

import com.parktech.sun.domain.model.notice.Notice;
import com.parktech.sun.domain.repository.BaseRepository;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.repository.notice.NoticeRepository;
import com.parktech.sun.domain.service.impl.BaseServiceImpl;
import com.parktech.sun.domain.service.notice.NoticeService;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User: Think
 * Date: 11-1-12
 * Time: 下午7:09
 */
@Service("noticeService")
public class NoticeServiceImpl extends BaseServiceImpl<Notice> implements NoticeService {

    private NoticeRepository noticeRepository;
    @Autowired
    public NoticeServiceImpl(NoticeRepository noticeRepository) {
        super(noticeRepository);
        this.noticeRepository = noticeRepository;
    }

    public Page<Notice> search(String title, Integer publishStatus, Page page) {

        Criteria criteria = noticeRepository.createCriteria();

        if (StringUtils.isNotEmpty(title)) {
            criteria.add(Property.forName("title").like(title, MatchMode.ANYWHERE));
        }

        if (publishStatus != -1) {
            criteria.add(Property.forName("publishStatus").eq(publishStatus));
        }

        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));

        return noticeRepository.page(criteria, page);
    }

    public Page pageBy(Page page) {

        Criteria criteria = noticeRepository.createCriteria();

        criteria.add(Property.forName("publishStatus").eq(1));
        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));

        return noticeRepository.page(criteria, page);
    }

    public List<Notice> getTopN(int n) {

        Criteria criteria = noticeRepository.createCriteria();

        criteria.add(Property.forName("publishStatus").eq(1));
        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));
        criteria.setMaxResults(n);

        return criteria.list();
    }
}
